package io.gitee.cdw.sensitive.autoconfigure;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.gitee.cdw.sensitive.serializer.JacksonSensitiveBeanSerializerModifier;
import io.gitee.cdw.sensitive.serializer.SensitiveSerializer;
import io.gitee.cdw.sensitive.strategy.StrategyManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * @author Created by chendw on 2024/1/19 12:52.
 */
@Slf4j
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(ObjectMapper.class)
public class SensitiveJackson2Configuration {

    @Bean
    public JacksonSensitiveBeanSerializerModifier sensitiveBeanSerializerModifier(StrategyManager strategyManager, SensitiveSerializer serializer) {
        return new JacksonSensitiveBeanSerializerModifier(strategyManager, serializer);
    }

    @Bean
    public WebMvcConfigurer webMvcConfigurer(@Autowired(required = false) JacksonSensitiveBeanSerializerModifier beanSerializerModifier) {
        return new WebMvcConfigurer() {
            @Override
            public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
                for (HttpMessageConverter<?> converter : converters) {
                    if (converter instanceof MappingJackson2HttpMessageConverter) {
                        ObjectMapper mapper = ((MappingJackson2HttpMessageConverter) converter).getObjectMapper();
                        mapper.setSerializerFactory(mapper.getSerializerFactory().withSerializerModifier(beanSerializerModifier));
                        log.debug("Init MappingJackson2HttpMessageConverter add beanSerializerModifier");
                        return;
                    }
                }
            }
        };
    }
}
